package com.wbs.shop.nuby.api;


import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

/**
 * Created by Jam on 16-5-17
 * Description:
 */
public class Api<T> {
    public final static long TIME_OUT = 30;
    public final static long WRITE_TIME_OUT = 3;
    private T SERVICE;
    private String host;

    public Api(String host, Class<T> tClass, Interceptor... interceptor) {
        this.host = host;
        if (SERVICE == null) {
            SERVICE = buildRetrofit(host, buildOkHttpClient(interceptor), tClass);
        }
    }

    public T getDefault() {
        return SERVICE;
    }

    public String getHost() {
        return host;
    }

    private static OkHttpClient buildOkHttpClient(Interceptor... interceptors) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        builder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        builder.writeTimeout(WRITE_TIME_OUT, TimeUnit.MINUTES);
        for (Interceptor interceptor : interceptors) {
            builder.addInterceptor(interceptor);
        }
        return builder.build();
    }

    private static <T> T buildRetrofit(String host, OkHttpClient client, Class<T> clz) {
        return new Retrofit.Builder()
                .baseUrl(host)
                .addConverterFactory(FastJsonConverterFactory.create())
//                .addConverterFactory(ParameterConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build().create(clz);
    }

//    public static <T extends UploadFileModel> List<MultipartBody.Part> filesToMultipartBodyParts(List<T> files, JSONObject paramJosn) {
//        MultipartBody.Builder builder = new MultipartBody.Builder();
//        builder.setType(MultipartBody.FORM); //表单类型
//
//        if (paramJosn != null) {
//            Logger.e(paramJosn.toString());
//            for (Map.Entry<String, Object> entry : paramJosn.entrySet()) {
//                builder.addFormDataPart(entry.getKey(), StringUtil.toString(entry.getValue()));
//            }
//        }
//        if (files != null) {
//            for (UploadFileModel uploadFileModel : files) {
//                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(uploadFileModel.getFilePath()));
//                builder.addFormDataPart(uploadFileModel.getFieldName(), uploadFileModel.getFieldName(), requestBody);
//            }
//        }
//        return builder.build().parts();
//    }
}
